<template>
	<el-form label-width="70px" size="small">
		{{ searchObj }}

		<el-form-item>
			<!-- 品牌列表 -->
			请选择品牌：
			<el-select
				v-model="searchObj.brandId"
				class="m-2"
				placeholder="Select"
				style="width: 240px"
			>
				<el-option
					v-for="item in brandList"
					:key="item.id"
					:label="item.name"
					:value="item.id"
				/>
			</el-select>

			请选择分类：
			<!-- searchCategoryIdList = [] 用来记录选择的三个分类id  -->
			<el-cascader
				:props="categoryProps"
				style="width: 20%"
				v-model="searchCategoryIdList"
			/>
			{{ searchCategoryIdList }}
		</el-form-item>

		<el-row style="display:flex">
			<el-button type="primary" size="small" @click="fetchData">
				搜索
			</el-button>
			<el-button size="small" @click="reset">重置</el-button>
		</el-row>
	</el-form>

	<div class="tools-div">
		<el-button type="success" size="small" @click="addShow">添 加</el-button>
	</div>

	<el-table :data="list" style="width: 100%">
		<el-table-column prop="categoryName" label="分类名称" />
		<el-table-column prop="brandName" label="品牌名称" />

		<el-table-column label="品牌logo" #default="scope">
			<img :src="scope.row.logo" width="50" />
		</el-table-column>

		<el-table-column prop="createTime" label="创建时间" />
        <el-table-column prop="categoryId" label="categoryId" />

		<el-table-column label="操作" align="center" width="200" #default='scope'>
			<el-button type="primary" size="small"  @click="editShow(scope.row)">
				修改
			</el-button>
			<el-button type="danger" size="small" @click="remove(scope.row.id)">
				删除
			</el-button>
		</el-table-column>
	</el-table>

	<el-pagination
		:page-sizes="[1, 2, 3, 4]"
		layout="total, sizes, prev, pager, next"
		:total="total"
		v-model:current-page="pageParam.pageNum"
		v-model:page-size="pageParam.pageSize"
		@size-change="fetchData"
		@current-change="fetchData"
	/>

    <!-- :before-close="handleClose" -->

	<el-dialog v-model="dialogVisible" title="添加/修改" width="50%" :before-close="handleClose" >
		{{ categoryBrand }}
		<el-form label-width="70px" size="small">
			<el-form-item label="选择品牌">
				<el-select
					v-model="categoryBrand.brandId"
					class="m-2"
					placeholder="Select"
					style="width: 240px"
				>
					<el-option
						v-for="item in brandList"
						:key="item.id"
						:label="item.name"
						:value="item.id"
					/>
				</el-select>
			</el-form-item>

			<el-form-item label="选择分类">
				<el-cascader
					:props="categoryProps"
					style="width: 240px"
					v-model="categoryBrand.categoryId"
				/>
			</el-form-item>

			<el-row style="display:flex">
				<el-button type="primary" size="small" @click="submitCategoryBrand">
					提交
				</el-button>
				<el-button type="default" size="small">
					取消
				</el-button>
			</el-row>
		</el-form>
	</el-dialog>
</template>

<script setup>
	import { ref, onMounted } from 'vue'

	import { CategoryBrandList, AddCategoryBrand,GetIdsByCategory3Id,UpdateCategoryBrandById,DeleteCategoryBrandById } from '@/api/categoryBrand'
	import { FindAll } from '@/api/brand'
	import { FindByParentId } from '@/api/category'
	import { ElMessage, ElMessageBox } from 'element-plus'

	// 定义表格数据模型
	const list = ref([])

	// 分页条数据模型
	const total = ref(0)

	//定义分页参数
	let pageParam = ref({
		pageNum: 1,
		pageSize: 2,
	})

	//查询条件（品牌id + 分类id）
	let searchObj = ref({
		brandId: '',
		categoryId: '',
	})

	let fetchData = async () => {
		//从数组中获取第三个分类id，赋值给searchObj.categoryId属性
		if (searchCategoryIdList.value.length == 3) {
			searchObj.value.categoryId = searchCategoryIdList.value[2]
		}

		let { data } = await CategoryBrandList(
			pageParam.value.pageNum,
			pageParam.value.pageSize,
			searchObj.value
		)
		//data 就是 pageInfo
		list.value = data.list
		total.value = data.total
	}

	onMounted(() => {
		fetchData()
		getBrandList()
	})

	let brandList = ref([
		{ id: 1, name: '测试1' },
		{ id: 2, name: '测试2' },
	])

	let getBrandList = async () => {
		let { data } = await FindAll()
		brandList.value = data
	}

	//级联选择器绑定的数组，用于存储三个分类id
	let searchCategoryIdList = ref([])

	//级联选择绑定的对象，若干属性
	let categoryProps = ref({
		lazy: true, //级联选择器具有懒加载效果（点击某个节点后，才会发起新的请求去查询下级分类列表）,
		value: 'id', //选择某个分类后，将分类id属性赋值到 searchCategoryIdList 数组中
		label: 'name', //每个选项需要显示的内容，显示分类对象的name属性
		leaf: 'leaf', // 记录分类对象中的那个属性用来表示当前节点是否是叶子节点，如果是叶子节点，就没有下级了，前端的效果就是没有>了（该属性=  !hasChildren）
		async lazyLoad(node, resolve) {
			// node.value //当前所点击节点的主键（分类id）
			let { data } = await FindByParentId(
				typeof node.value == 'undefined' ? 0 : node.value
			)
			data.forEach(element => {
				// console.log(element)
				element.leaf = !element.hasChildren
			})
			resolve(data) //将查询到的分类列表，传入到resolve方法中
		},
	})

	let reset = () => {
		searchCategoryIdList.value = []
		searchObj.value.brandId = ''
		searchObj.value.categoryId = ''
		fetchData()
	}

	let dialogVisible = ref(false)

	let addShow = () => {
		dialogVisible.value = true
		categoryBrand.value.brandId = ''
		categoryBrand.value.categoryId = ''
	}

	let categoryBrand = ref({
		brandId: '',
		categoryId: '',
	})

	let submitCategoryBrand = async () => {
		if (categoryBrand.value.categoryId.length != 3) {
			ElMessage.warning('请选择三级商品分类')
			return
		}

		if (categoryBrand.value.brandId == '') {
			ElMessage.warning('请选择品牌')
			return
		}

		//将三级分类id单独取出赋值给categoryBrand.value.categoryId
		categoryBrand.value.categoryId = categoryBrand.value.categoryId[2]

		if (!categoryBrand.value.id) {
					let { code, message } = await AddCategoryBrand(categoryBrand.value)
				if (code == 200) {
					ElMessage.success('建立成功')
					dialogVisible.value = false
					fetchData()
				} else {
					ElMessage.warning('建立失败,' + message)
				}


			} else {
				let { code, message } = await UpdateCategoryBrandById(categoryBrand.value)
				if (code == 200) {
					ElMessage.success('建立成功')
					dialogVisible.value = false
					fetchData()
				} else {
					ElMessage.warning('建立失败,' + message)
				}

			}
		

		/* let { code, message } = await AddCategoryBrand(categoryBrand.value)
		if (code == 200) {
			ElMessage.success('建立成功')
			dialogVisible.value = false
			fetchData()
		} else {
			ElMessage.warning('建立失败,' + message)
		} */
	}


    let editShow = async (row)=>{
        //弹窗打开
        dialogVisible.value = true

        // categoryBrand.value.brandId = row.brandId
        // categoryBrand = { brandId:xx,categoryId:xx } 是弹窗上两个控件需要绑定的对象变量 
        // 将当前行数据赋值给categoryBrand， 此时品牌下拉框就会自动回显  ，因为categoryBrand.brandId 有值，categoryBrand.categoryId 也有值
        //但是 分类的级联选择器并未回显，因为什么？  因为分类id只是第三级分类id
        //级联选择器怎么回显3个分类？ categoryBrand.categoryId = [ 3个分类id ]
        categoryBrand.value = row //row（品牌id，分类id，品牌名称，分类名称，品牌logo ....）

        //根据第三级分类id，查询上级和上上级分类id，返回分类id集合 [1,2,3]
        let {data} = await GetIdsByCategory3Id(row.categoryId)
        categoryBrand.value.categoryId = data

    }

    //点击弹窗的X 
    let handleClose = ()=>{
        dialogVisible.value = false
        fetchData() //关闭弹窗为何要重新加载表格数据？  
        //将row赋值给弹窗的categoryBrand对象（他俩指向同一个对象），
        //然后执行categoryBrand.value.categoryId = data 修改categoryBrand对象的属性,相当于将row的categoryId也修改了
    }

			const remove = async id => {
		ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', 'Warning', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		})
			.then(async () => {
			await DeleteCategoryBrandById(id)
			ElMessage.success('删除成功')
			fetchData()
			})
			.catch(() => {
			ElMessage.info('取消删除')
			})
		}

	
</script>

<style scoped>
	.tools-div {
		margin: 10px 0;
		padding: 10px;
		border: 1px solid #ebeef5;
		border-radius: 3px;
		background-color: #fff;
	}
</style>